package Rights;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.naming.NoPermissionException;

import Public.iRights;

public class RightsService implements iRights {
	private ArrayList<PairAppfunctionGroup> rightsCache;
	private RightsadmissionService rightsadmissionService;
	private static BufferedReader inStream;
	final private static String permissionsPath = "\\Permission\\Permissions.txt";
	public RightsService() {
		this.rightsadmissionService = RightsadmissionService.getRightsadmissionService();
	}
	
	@Override
	public UserTicket authenticate(String user,String password) {
		UserTicket result = this.rightsadmissionService.authenticate(user, password);
		if(result == null) {
			return null;
		}
		return result;
	}
	
	@Override
	public boolean isAccessPermitted(UserTicket user,ApplicationFunction function) {
		try {
			updateRightsCache();
			PairAppfunctionGroup requestPair = new PairAppfunctionGroup(function,user.getUserGroup());
			if(this.rightsCache.contains(requestPair)) {
				return true;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	private void initStreams() throws FileNotFoundException {
		inStream = new BufferedReader(new FileReader(permissionsPath));
	}

	private void updateRightsCache() throws IOException,FileNotFoundException {
		initStreams();
		String line;
		while((line = inStream.readLine()) != null) {
			String[] parts = line.split(";");
			if(parts.length != 2) throw new RuntimeException();
			try {
				rightsCache.add(new PairAppfunctionGroup(new ApplicationFunction(parts[0]), new UserGroup(new Integer(parts[1]))));
			} catch (Throwable t) { t.printStackTrace(); }
		}
	}
	
}
